<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <VGroup>
          <el-select v-model="form.dateRange.type" style="width: 100px">
            <el-option label="创建时间" value="created"></el-option>
            <el-option label="发布时间" value="send"></el-option>
            <el-option label="修改时间" value="updated"></el-option>
          </el-select>
          <el-date-picker
            v-model="form.dateRange.value"
            clearable
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            style="width: 400px"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="defaultTime"
          />
        </VGroup>
        <VGroup>
          <el-select v-model="form.user.type" style="width: 100px">
            <el-option label="创建人" value="createUserIds"></el-option>
            <el-option label="修改人" value="updateUsers"></el-option>
          </el-select>
          <VCascader
            v-model="form.user.value"
            collapse-tags
            style="width: 200px"
            placeholder="请选择"
          />
        </VGroup>
        <el-select
          v-model="form.status"
          placeholder="状态"
          style="width: 100px"
          clearable
        >
          <el-option
            v-for="item in optionsData?.['message_state'] || []"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-select
          v-model="form.messageType"
          placeholder="通知类型"
          style="width: 100px"
          clearable
        >
          <el-option
            v-for="item in optionsData?.['message_type'] || []"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-input
          v-model="form.title"
          style="width: 200px"
          clearable
          placeholder="通知标题"
        ></el-input>
      </template>
      <template #toolbar_btns>
        <el-button
          type="primary"
          @click="addVisible = true"
          icon="Plus"
          v-hasPermi="[userSysAuthList.notice.add]"
          >新增</el-button
        >
      </template>
      <template #operation="{ row }">
        <el-button
          v-if="row.status.value !== 2"
          link
          type="primary"
          @click="handleEdit(row.id)"
          v-hasPermi="[userSysAuthList.notice.edit]"
        >
          编辑
        </el-button>
        <el-button link type="primary" @click="handleDetails(row.id)">
          详情
        </el-button>
        <el-button
          v-if="row.status.value == 2"
          link
          type="danger"
          @click="handleRevocation(row.id)"
          v-hasPermi="[userSysAuthList.notice.recall]"
        >
          撤回
        </el-button>
        <el-button
          v-if="row.status.value !== 2"
          link
          type="danger"
          @click="handleDelete(row.id)"
          v-hasPermi="[userSysAuthList.notice.delete]"
        >
          删除
        </el-button>
      </template>
    </VTable>
    <Add
      v-model="addVisible"
      :id="addId"
      :options="optionsData"
      @refresh="refresh"
      @close="addId = ''"
    />
    <Details v-model="detailsVisible" :id="detailsId" @close="detailsId = ''" />
  </VPage>
</template>
<script setup lang="jsx">
import { ElMessage } from "element-plus";
import Add from "./components/Add/index";
import { defaultTime } from "./data.js";
import Details from "./components/details/index";
import { messageRecall, messageDelete, messageList, dictionary } from "./api";
import { userSysAuthList } from "@/Auth/userSys.js";
import { isPermission } from "@/hooks/permission.js";
const { proxy } = getCurrentInstance();
const tableRef = ref();

const tableOptins = reactive({
  formConfig: {
    data: {
      dateRange: { type: "created", value: [] }, // 组合+日期范围
      user: { type: "createUserIds", value: [] },
    },
  },
  columns: [
    { fixed: "left", width: 50, type: "checkbox" },
    { fixed: "left", width: 50, title: "ID", field: "id" },
    {
      fixed: "left",
      title: "通知标题",
      minWidth: 200,
      field: "title",
    },
    {
      title: "通知类型",
      width: 100,
      field: "messageType.label",
      slots: {
        default: ({ row }) => {
          return <div>{row?.messageType?.label || "-"}</div>;
        },
      },
    },
    {
      title: "发布方式",
      width: 100,
      field: "sendType.label",
      slots: {
        default: ({ row }) => {
          return <div>{row?.sendType?.label || "-"}</div>;
        },
      },
    },
    {
      title: "弹窗等级",
      width: 200,
      field: "popLevel.label",
      slots: {
        default: ({ row }) => {
          return <div>{row?.popLevel?.label || "-"}</div>;
        },
      },
    },
    {
      title: "是否同步飞书",
      width: 120,
      field: "isSyncFeishu.label",
      slots: {
        default: ({ row }) => {
          return <div>{row?.isSyncFeishu?.label || "-"}</div>;
        },
      },
    },
    {
      title: "状态",
      width: 100,
      field: "time_val_status",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <el-tag
                type={
                  row.status.value == 2
                    ? "warning"
                    : row.status.value == 1
                    ? "primary"
                    : "danger"
                }
              >
                {row.status.label}
              </el-tag>
            </div>
          );
        },
      },
    },
    { title: "已读人数", minWidth: 200, field: "viewed" },
    { title: "创建时间", width: 170, field: "createdAt" },
    { title: "创建人", width: 170, field: "createUser" },
    { title: "发布时间", width: 170, field: "sendTime" },
    { title: "修改时间", width: 170, field: "updatedAt" },
    { title: "修改人", width: 170, field: "updateUser" },
    {
      title: "操作",
      width: 160,
      fixed: "right",
      slots: { default: "operation" },
    },
  ],
  proxyConfig: {
    autoLoad: false, // 是否自动加载查询数据
    props: {
      result: "data",
      total: "total",
    },
    ajax: {
      query: ({ page, form }) => {
        let { created = [], send = [], updated = [] } = form;
        let params = {
          ...form,
          createdStartAt: created[0] || "",
          createdEndAt: created[1] || "",
          startSendTime: send[0] || "",
          endSendTime: send[1] || "",
          updatedEndAt: updated[1] || "",
          updatedStartAt: updated[0] || "",
          created: "",
          send: "",
          updated: "",
        };
        return messageList({ ...page, ...params }).then((res) => {
          return {
            data: res.data,
            total: res.total,
          };
        });
      },
    },
  },
});
const optionsData = ref({});
const getOption = async () => {
  const { data } = await dictionary({
    enums: "message_type,send_type,notice_type,pop_level,bool,message_state",
  });
  optionsData.value = data || {};
};
getOption();
const addVisible = ref(false);
const addId = ref(null);
const handleEdit = (id) => {
  addId.value = id;
  addVisible.value = true;
};
const detailsVisible = ref(false);
const detailsId = ref(null);
const handleDetails = (id) => {
  detailsId.value = id;
  detailsVisible.value = true;
};
const handleDelete = (id) => {
  proxy?.confirm({
    title: "提示",
    content: (
      <p>
        确认删除选中的
        <span class="text-[#3366F1] px-[4px]">{id.length || 1}</span>
        条数据？
      </p>
    ),
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          const { code, message } = await messageDelete({ id });
          if (code != 200) {
            ElMessage.error(message);
            return;
          }
          ElMessage.success("删除成功!");
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          refresh();
        }
      } else {
        done();
      }
    },
  });
};

const handleRevocation = (id) => {
  proxy?.confirm({
    title: "提示",
    content: (
      <p>
        确认撤回选中的
        <span class="text-[#3366F1] px-[4px]">{id.length || 1}</span>
        条数据？
      </p>
    ),
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          const { code, message } = await messageRecall({ id });
          if (code != 200) {
            ElMessage.error(message);
            return;
          }
          ElMessage.success("撤回成功!");
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          refresh();
        }
      } else {
        done();
      }
    },
  });
};

//更新表格数据
const refresh = () => {
  tableRef?.value.$table.commitProxy("query");
};
</script>
